#include "mainform.h"
#include "ui_mainform.h"

#include "collapseview.h"
#include "colorpickform.h"


#include <QDebug>
#include <QDesktopWidget>
#include <QApplication>
#include <QMessageBox>
#include <wsim/websocket_common.h>
#include "../wsim_client.h"
#include <QMetaType>
#include <QDir>
#include <QFile>
#include <QSystemTrayIcon>
#include <QMenu>
#include "../model/collectiongrabwindow.h"
#include "../model/transferfromqthread.h"
#include "../model/virtualkey.h"
#include "dialogreguser.h"

#include <linux/uinput.h>

//主串口与屏幕边缘的距离
int MAIN_FORM_OADDING =10;

MainForm::MainForm(int fd,QWidget *parent) :
    MoveableFramelessWindow(parent),
    ui(new Ui::MainForm)
{
    ui->setupUi(this);

    //qDebug()<<this;
    setObj(this);
    wsfd=fd;
    pCollapseView=new CollapseView(wsfd);
    pCollapseView_2=new CollapseView(wsfd);
    pCollapseView_3=new CollapseView(wsfd);
    m_teamMap.clear();

    //加入联系人列表
    ui->page_4->layout()->addWidget(pCollapseView);
    ui->page_5->layout()->addWidget(pCollapseView_2);
    ui->page_6->layout()->addWidget(pCollapseView_3);
    //关联切换皮肤颜色按钮事件
    connect(ui->pushButton_skin,SIGNAL(clicked()),this,SLOT(doChangeColor()));
    connect(ui->lineEdit_mood, SIGNAL(editingFinished()), this, SLOT(doReMood()));
    //connect(ui->lineEdit_mood, SIGNAL(returnPressed()), this, SLOT(doReMood()));
    //关闭
    connect(ui->pushButton_close,SIGNAL(clicked()),this,SLOT(doClose()));
    //更新客户列表
    connect(ui->pushButton_t,SIGNAL(clicked()),this,SLOT(doReClientList()));
    connect(ui->pushButton_p,SIGNAL(clicked()),this,SLOT(doReOrganClientList()));
    connect(ui->pushButton_q,SIGNAL(clicked()),this,SLOT(doReGroupClientList()));

    //获取屏幕
    QDesktopWidget* desktopWidget = QApplication::desktop();

    //得到屏幕宽度
    int screenWidth = desktopWidget->width();

    //转移到右边
    this->move(screenWidth-MAIN_FORM_OADDING-this->width(),MAIN_FORM_OADDING);

    //新建QSystemTrayIcon对象
    pSysTrayIcon = new QSystemTrayIcon(this);
    //新建托盘要显示的    icon
    QIcon icon = QIcon(":/sys/qlogo.png");
    //将icon设到QSystemTrayIcon对象中
    pSysTrayIcon->setIcon(icon);
    //当鼠标移动到托盘上的图标时，会显示此处设置的内容
    pSysTrayIcon->setToolTip(ui->label_nick->text());

     tray_menu = new QMenu(this);
    QAction    *m_action1 = new QAction("显示窗口",tray_menu);
    QAction    *m_action2 = new QAction("传送列表",tray_menu);
     QAction    *m_action_close = new QAction("退出",tray_menu);


        tray_menu->addAction(m_action1);
        tray_menu->addAction(m_action2);
        tray_menu->addSeparator();
     tray_menu->addAction(m_action_close);

        connect(m_action1, SIGNAL(triggered()), this, SLOT(showWindow()));
        connect(m_action2, SIGNAL(triggered()), this, SLOT(showTransfer()));
        connect(ui->pushButton_mail,SIGNAL(clicked()),this,SLOT(showTransfer()));
     connect(m_action_close, SIGNAL(triggered()), this, SLOT(doClose()));
     connect(pSysTrayIcon,SIGNAL(clicked()),this,SLOT(onTrayClick()));
        pSysTrayIcon->setContextMenu(tray_menu);

        //在系统托盘显示此对象
        pSysTrayIcon->show();



            pTeamVK=new VirtualKey();

    connect(ui->pushButton_zone,SIGNAL(clicked()),this,SLOT(doRegUser()));

}

MainForm::~MainForm()
{

    delete pTeamVK;
    delete pCollapseView;
    delete pCollapseView_2;
    delete pCollapseView_3;

    delete tray_menu;
    delete pSysTrayIcon;
    delete ui;
}
void MainForm::onTrayClick()
{
    tray_menu->show();
}

void MainForm::showWindow()
{
    if(this->isVisible())
        this->hide();
    else
        this->show();
}
void MainForm::showTransfer()
{
    MY_TRANSFER_FORM.show();
    MY_TRANSFER_FORM.raise();
    MY_TRANSFER_FORM.setFocus();

    transferForm*f=&(MY_TRANSFER_FORM);
    if(f!=NULL){
        f->setTitle(ui->label_nick->text());
    }

}
void MainForm::doRegUser()
{
    WSIM_client::readUserInfo(ui->label_nick->text().toStdString());
    dialogReg.setWindowTitle(ui->label_nick->text()+" 注册信息");
    dialogReg.setNickName(ui->label_nick->text());
    dialogReg.setName(QString::fromStdString(this->server_name));
    dialogReg.setOrgan(QString::fromStdString(this->server_organ));
    dialogReg.setMobile(QString::fromStdString(this->server_mobileNumber));
    dialogReg.setGroups(QString::fromStdString(this->server_group));
    dialogReg.exec();

}
void MainForm::doReMood()
{
    //此处判断如果焦点存在，执行（响应enter，屏蔽失去焦点事件）
      if(ui->lineEdit_mood->hasFocus()==false)
      {

    QString mood=ui->lineEdit_mood->text();
    //qDebug()<<mood;
    WSIM_client::reMood(mood.toStdString());
      }
}


void MainForm::setNickname(QString nickname)
{
    ui->label_nick->setText(nickname);
    pSysTrayIcon->setToolTip(nickname);
}
void MainForm::doChangeColor()
{

    MY_COLOR_PICK_FORM.show();
    MY_COLOR_PICK_FORM.raise();
    MY_COLOR_PICK_FORM.setFocus();

    ColorPickForm*f=&(MY_COLOR_PICK_FORM);

    connect(f,SIGNAL(themColorChanged(QString)),this,SLOT(onThemeColorChange(QString)));

}
void MainForm::doReClientList()
{

    WSIM_client::readClients();

    ui->page_4->show();
    ui->page_5->hide();
    ui->page_6->hide();
}
void MainForm::doReOrganClientList()
{
    //WSIM_client::readRegClients();

    ui->page_4->hide();
    ui->page_5->show();
    ui->page_6->hide();
}
void MainForm::doReGroupClientList()
{
     WSIM_client::readOrganUser(this->server_organ);
    //WSIM_client::readGroupUser(this->server_group);
    ui->page_4->hide();
    ui->page_5->hide();
    ui->page_6->show();
}
void MainForm::onCloseWS()
{
    QString msg="服务器已关闭，请重新连接登录......";
    QMessageBox::about(this,"服务断开",msg);
}

void MainForm::doClose()
{
    if(QMessageBox::question(this,"关闭","隐藏或退出？\n是(Yes)退出，否(No)隐藏",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes){
       WSIM_client::closefd();
    ColorPickForm*f=&(MY_COLOR_PICK_FORM);
    if(f!=NULL)
        f->close();

    transferForm*pTransferView=&(MY_TRANSFER_FORM);
    if(pTransferView!=NULL)
        pTransferView->close();

    if(pCollapseView!=NULL)
        pCollapseView->closeCollapses();
    if(pCollapseView_2!=NULL)
        pCollapseView_2->closeCollapses();
    if(pCollapseView_3!=NULL)
        pCollapseView_3->closeCollapses();
    this->close();
    }
    else
    {
        this->hide();
    }

}
void MainForm::onThemeColorChange(QString colorStr)
{
    //组合成qcc样式表
    QString style=QString("#%1{background-color:%2;}").arg(ui->centralwidget->objectName(),colorStr);
    //定义样式
    ui->centralwidget->setStyleSheet(style);
    if(pCollapseView!=NULL)
        pCollapseView->onThemeColorChange(colorStr);
    if(pCollapseView_2!=NULL)
        pCollapseView_2->onThemeColorChange(colorStr);
    if(pCollapseView_3!=NULL)
        pCollapseView_3->onThemeColorChange(colorStr);

    transferForm*f=&(MY_TRANSFER_FORM);
    if(f!=NULL)
        f->onThemeColorChange(colorStr);
}

QWidget *MainForm::getDragnWidget()
{
    return ui->main_top;
}

/**
 * @brief MainForm::slotAddClient  添加一个用户
 * @param item
 */
void MainForm::slotAddClient(clientItem item,int t)
{
    //QMessageBox::information(this,item.uuid,item.nickname,QMessageBox::Ok);
    if(t==2){
    if(pCollapseView_2!=NULL)
    {
        pCollapseView_2->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
    }
    }
    else if(t==3){
    if(pCollapseView_3!=NULL)
    {
        pCollapseView_3->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
    }
    }
    else if(t==1){
    if(pCollapseView!=NULL)
    {
        pCollapseView->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
    }
    }
    else if(t==0){
        if(item.breg){
            if((server_organ.compare(item.organ.toStdString())==0)&&(item.organ.length()>0))
            {
                if(pCollapseView_3!=NULL)
                {
                    pCollapseView_3->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
                }
            }
            else{
            if(pCollapseView_2!=NULL)
            {
                pCollapseView_2->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
            }
            }
            }
        else{
            if(pCollapseView!=NULL)
            {
                pCollapseView->addCollapse(item.fd,item.uuid,item.nickname,item.mood);
            }
        }
    }
}
void MainForm::slotDropClient(clientItem item)
{
    //QMessageBox::warning(this,item.uuid,item.nickname,QMessageBox::Ok);
    if(pCollapseView!=NULL)
    {
        pCollapseView->delCollapse(item.fd,item.uuid,item.nickname);
    }
    if(pCollapseView_2!=NULL)
    {
        pCollapseView_2->delCollapse(item.fd,item.uuid,item.nickname);
    }
    if(pCollapseView_3!=NULL)
    {
        pCollapseView_3->delCollapse(item.fd,item.uuid,item.nickname);
    }
}
void MainForm::slotMessage(WS_MESSAGE msg)
{
    if(pCollapseView!=NULL)
    {
        pCollapseView->readMessage(msg);
    }
    if(pCollapseView_2!=NULL)
    {
        pCollapseView_2->readMessage(msg);
    }
    if(pCollapseView_3!=NULL)
    {
        pCollapseView_3->readMessage(msg);
    }
}
void MainForm::slot_wsFile(wsimBIN_head head)
{
    //qDebug()<<"文件:"<<head.label<<"接收完成...处理";
    int i=WSIM_client::findLinkUp(0,head.fromfd,head.magic);
    if(i>=0){
/*

            //qDebug()<<"接收完成，开始整理数据...";
            QString filename=QString("%1_%2").arg(head.label).arg(head.magic);
               QString m_fileName=QString("/tmp/%1").arg(filename);

    //发送完成消息
    if(pCollapseView!=NULL){
            QMap<QString,clientItem*>::iterator it;
                for( it=pCollapseView->m_clientMap.begin(); it!=pCollapseView->m_clientMap.end(); it++)
                {
                    if(it.value()->fd==head.fromfd)
                    {
                        WS_MESSAGE wsmsg;
                        wsmsg.f_fd=head.fromfd;
                        wsmsg.f_nickname=it.value()->nickname;
                        wsmsg.f_uuid=it.value()->uuid;
                        wsmsg.message=QString::fromStdString(head.label)+"传送完成！！！已保存为："+m_fileName;
                        pCollapseView->readMessage(wsmsg);
                        break;
                    }
                }


    }

      */
                    WSIM_client::delLinkUp(0,head.fromfd,head.magic);

 }
}
void MainForm::slot_wsTransfer(int tfd, int ffd, int magic, int index)
{
    //qDebug()<<"接收进度"<<index;
    transferForm*t=&(MY_TRANSFER_FORM);
    if(t!=NULL){
        t->updateProgress(tfd,ffd,magic,index);
    }

}
/**
 * @brief MainForm::slot_wsRequest  收到对方发送来的请求，提示并出所响应
 * @param ffd
 * @param magic
 * @param request
 * @param item
 */
void MainForm::slot_wsRequest(int ffd, int magic, QString request,linkItem item)
{
    if(QMessageBox::question(this,"请求",request,QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)==QMessageBox::Yes)
    {

       WSIM_client::addLinkItem(item);
       WSIM_client::sendResponse(ffd,magic,"yes");
       transferForm*t=&(MY_TRANSFER_FORM);
       if(t!=NULL)
           t->addItem(0,ffd,magic,item.maxPageNum,QString::fromStdString(item.label));
    }
    else
        WSIM_client::sendResponse(ffd,magic,"no");
}

void MainForm::slot_wsTeamClose(int tfd, int ffd, int magic)
{
    QString teamKey=QString("Team_%1_%2_%3").arg(tfd).arg(ffd).arg(magic);
    if(m_teamMap.contains(teamKey))
    {
        TeamForm* pForm=m_teamMap[teamKey];
        if(pForm!=NULL)
            pForm->close();

        m_teamMap.remove(teamKey);
    }
}
void MainForm::slot_wsTeamCommand(int tfd,int ffd,int magic,QString command)
{
    //获取全局鼠标位置
    QPoint coursePoint;
    coursePoint = QCursor::pos();//获取当前光标的位置

    //qDebug()<<command;
    if(command.compare("closeTeam")==0)
    {
        collectionGrabWindow*pix=&(MY_COLLECTION_GRABWINDOW);
        if(pix!=NULL)
        {
            if(pix->isCollection())
                pix->setCollection(false);
        }

    }/*
    else if(command.indexOf("mouseMove(")==0)
    {
        command.remove(QRegExp("^(mouseMove+)"));
        command.remove(0,1);
        command.remove(command.size()-1,1);
        QStringList postlist = command.split(",", QString::SkipEmptyParts);
        if(postlist.size()==3)
        {
            QString btStr=postlist.at(2);
            int newx=postlist.at(0).toInt()/0.7;
            int newy=postlist.at(1).toInt()/0.7;
            int x=newx-coursePoint.x();
            int y=newy-coursePoint.y();
            if(pTeamVK!=NULL)
            {
                pTeamVK->moveMouse(x,y);
                if(btStr.compare("LeftButton")==0){
                    pTeamVK->keyPress(BTN_LEFT);
                }
                else if(btStr.compare("RightButton")==0){
                    pTeamVK->keyPress(BTN_RIGHT);
                }
            }
           }
    }*/
    else if(command.indexOf("mousePress(")==0)
    {
        command.remove(QRegExp("^(mousePress+)"));
        command.remove(0,1);
        command.remove(command.size()-1,1);
        QStringList postlist = command.split(",", QString::SkipEmptyParts);
        if(postlist.size()==3)
        {

            int newx=postlist.at(0).toInt()/0.7;
            int newy=postlist.at(1).toInt()/0.7;
            int x=newx-coursePoint.x();
            int y=newy-coursePoint.y();
            //qDebug()<<coursePoint;
            //qDebug()<<"new:"<<postlist.at(0).toInt()<<"/0.7="<<newx<<","<<postlist.at(1).toInt()<<"/0.7="<<newy;
            QString btStr=postlist.at(2);
            if(pTeamVK!=NULL)
            {

                pTeamVK->moveMouse(x,y);
                if(btStr.compare("LeftButton")==0){                    
                    pTeamVK->button(BTN_LEFT);
                }
                else if(btStr.compare("RightButton")==0){
                    pTeamVK->button(BTN_RIGHT);
                }
            }

        }
    }
    else if(command.indexOf("keyButton(")==0)
    {
        command.remove(QRegExp("^(keyButton+)"));
        command.remove(0,1);
        command.remove(command.size()-1,1);
        QStringList postlist = command.split(",", QString::SkipEmptyParts);
        if(postlist.size()==2)
        {


            if(pTeamVK!=NULL)
            {
                int kInt=postlist.at(0).toInt();
                int Modifier=postlist.at(1).toInt();
                //qDebug()<<kInt;
                //ASCII转扫描码

                if(kInt==Qt::Key_Escape) kInt=KEY_ESC;
                else if(kInt==Qt::Key_QuoteLeft) kInt=KEY_GRAVE;                
                else if((kInt>=Qt::Key_1)&&(kInt<=Qt::Key_9)) kInt=kInt-Qt::Key_1+KEY_1;
                else if(kInt==Qt::Key_0) kInt=KEY_0;
                else if((kInt==Qt::Key_Minus)) kInt=KEY_MINUS;
                else if((kInt==Qt::Key_Equal)) kInt=KEY_EQUAL;
                else if((kInt==Qt::Key_Backspace)) kInt=KEY_BACKSPACE;
                else if((kInt==Qt::Key_Tab)) kInt=KEY_TAB;
                else if((kInt==Qt::Key_Q)) kInt=KEY_Q;
                else if((kInt==Qt::Key_W)) kInt=KEY_W;
                else if((kInt==Qt::Key_E)) kInt=KEY_E;
                else if((kInt==Qt::Key_R)) kInt=KEY_R;
                else if((kInt==Qt::Key_T)) kInt=KEY_T;
                else if((kInt==Qt::Key_Y)) kInt=KEY_Y;
                else if((kInt==Qt::Key_U)) kInt=KEY_U;
                else if((kInt==Qt::Key_I)) kInt=KEY_I;
                else if((kInt==Qt::Key_O)) kInt=KEY_O;
                else if((kInt==Qt::Key_P)) kInt=KEY_P;
                else if((kInt==Qt::Key_BracketLeft)) kInt=KEY_LEFTBRACE;
                else if((kInt==Qt::Key_BracketRight)) kInt=KEY_RIGHTBRACE;
                else if((kInt==Qt::Key_Backslash)) kInt=KEY_BACKSLASH;
                else if((kInt==Qt::Key_Return)) kInt=KEY_ENTER;
                else if((kInt==Qt::Key_CapsLock)) kInt=KEY_CAPSLOCK;
                else if((kInt==Qt::Key_A)) kInt=KEY_A;
                else if((kInt==Qt::Key_S)) kInt=KEY_S;
                else if((kInt==Qt::Key_D)) kInt=KEY_D;
                else if((kInt==Qt::Key_F)) kInt=KEY_F;
                else if((kInt==Qt::Key_G)) kInt=KEY_G;
                else if((kInt==Qt::Key_H)) kInt=KEY_H;
                else if((kInt==Qt::Key_J)) kInt=KEY_J;
                else if((kInt==Qt::Key_K)) kInt=KEY_K;
                else if((kInt==Qt::Key_L)) kInt=KEY_L;
                else if((kInt==Qt::Key_Semicolon)) kInt=KEY_SEMICOLON;
                else if((kInt==Qt::Key_Apostrophe)) kInt=KEY_APOSTROPHE;

                //else if((kInt==Qt::Key_Shift)) kInt=KEY_LEFTSHIFT;
                else if((kInt==Qt::Key_Z)) kInt=KEY_Z;
                else if((kInt==Qt::Key_X)) kInt=KEY_X;
                else if((kInt==Qt::Key_C)) kInt=KEY_C;
                else if((kInt==Qt::Key_V)) kInt=KEY_V;
                else if((kInt==Qt::Key_B)) kInt=KEY_B;
                else if((kInt==Qt::Key_N)) kInt=KEY_N;
                else if((kInt==Qt::Key_M)) kInt=KEY_M;
                else if((kInt==Qt::Key_Comma)) kInt=KEY_COMMA;
                else if((kInt==Qt::Key_Period)) kInt=KEY_DOT;
                else if((kInt==Qt::Key_Slash)) kInt=KEY_SLASH;
                //else if((kInt==Qt::Key_Shift)) kInt=KEY_RIGHTSHIFT;
                else if((kInt==Qt::Key_Space)) kInt=KEY_SPACE;
                else return;
                //qDebug()<<"扫描码"<<kInt;

                if(Modifier==Qt::ShiftModifier)
                    pTeamVK->keyPress(KEY_LEFTSHIFT);

                pTeamVK->button(kInt);

                if(Modifier==Qt::ShiftModifier)
                    pTeamVK->keyRelease(KEY_LEFTSHIFT);
            }

        }
    }
/*
    else if(command.indexOf("mouseRelease(")==0)
    {
        command.remove(QRegExp("^(mouseRelease+)"));
        command.remove(0,1);
        command.remove(command.size()-1,1);
        QStringList postlist = command.split(",", QString::SkipEmptyParts);
        if(postlist.size()==3)
        {
            int newx=postlist.at(0).toInt()/0.7;
            int newy=postlist.at(1).toInt()/0.7;
            int x=newx-coursePoint.x();
            int y=newy-coursePoint.y();

            QString btStr=postlist.at(2);
            if(pTeamVK!=NULL)
            {
                pTeamVK->moveMouse(x,y);
                if(btStr.compare("LeftButton")==0){
                    pTeamVK->keyRelease(BTN_LEFT);
                }
                else if(btStr.compare("RightButton")==0){
                    pTeamVK->keyRelease(BTN_LEFT);
                }
            }

        }
    }*/
    else if(command.indexOf("mouseDoubleClick(")==0)
    {
        command.remove(QRegExp("^(mouseDoubleClick+)"));
        command.remove(0,1);
        command.remove(command.size()-1,1);
        QStringList postlist = command.split(",", QString::SkipEmptyParts);
        if(postlist.size()==3)
        {
        int newx=postlist.at(0).toInt()/0.7;
        int newy=postlist.at(1).toInt()/0.7;
        int x=newx-coursePoint.x();
        int y=newy-coursePoint.y();

        QString btStr=postlist.at(2);
        if(pTeamVK!=NULL)
        {

            pTeamVK->moveMouse(x,y);
            //pTeamVK->absMouse(newx,newy);
                if(btStr.compare("LeftButton")==0){
                    pTeamVK->button(BTN_LEFT);
                    pTeamVK->button(BTN_LEFT);
                }

        }
        }
    }
    else
        qDebug()<<"未处理"<<command;
}

void MainForm::slot_wsTeamTransfer(int tfd, int ffd, int magic,int index, QByteArray barray)
{
    QString teamKey=QString("Team_%1_%2_%3").arg(tfd).arg(ffd).arg(magic);
    if(m_teamMap.contains(teamKey))
    {
        TeamForm* pForm=m_teamMap[teamKey];
        if(pForm!=NULL)
         {

            if(index==1)
            {

                pForm->newPixmap();
                pForm->appByte(barray);
            }
            else{
                pForm->appByte(barray);
            }
            //pForm->loadByteToPixmap();
        }
    }
    else
    {
        TeamForm* pForm=new TeamForm(ffd,magic);
        if(pForm!=NULL)
        {
            pForm->appByte(barray);
            pForm->show();
            m_teamMap.insert(teamKey,pForm);
        }
    }
}
